package com.hiv.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import com.google.common.collect.Lists;
import com.hiv.common.PageInfo;
import com.hiv.common.param.page.PageQuerySamplingBoxParam;
import com.hiv.mapper.BatchMapper;
import com.hiv.mapper.SamplingBoxMapper;
import com.hiv.mapper.SamplingBoxRecordMapper;
import com.hiv.mapper.SamplingRecordMapper;
import com.hiv.mapper.domain.Batch;
import com.hiv.mapper.domain.SamplingBox;
import com.hiv.mapper.domain.SamplingRecord;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采样盒子Service业务层处理
 *
 * @author zhanghong
 * @date 2022-09-20
 */
@Service
public class SamplingBoxService {
    @Autowired
    private SamplingBoxMapper samplingBoxMapper;
    @Autowired
    private SamplingBoxRecordMapper samplingBoxRecordMapper;
    @Autowired
    private SamplingRecordMapper samplingRecordMapper;
    @Autowired
    private BatchMapper batchMapper;

    /**
     * 分页查询
     * @param param
     * @return
     */
    public PageInfo<SamplingBox> pageQuery(PageQuerySamplingBoxParam param) {
        if (param.getSendType() != null && param.getSendType() == 1) {
            long count = samplingBoxMapper.pageCount(param);
            List<SamplingBox> list = samplingBoxMapper.pageQuery(param, param.getPageSize(), param.fetchOffSet());
            list.forEach(this::buildInfo);
            return new PageInfo<>(param.getPageNum(), param.getPageSize(), list, count);
        } else {
            List<SamplingBox> list = samplingBoxMapper.listCondition(param);
            if (CollectionUtils.isEmpty(list)) {
                return new PageInfo<>(param.getPageNum(), param.getPageSize(), Collections.emptyList(), 0);
            }

            Map<String, List<SamplingBox>> map = list.stream().collect(Collectors.groupingBy(SamplingBox::getExpress));
            List<SamplingBox> result = Lists.newArrayList();
            map.forEach((key,values) -> {
                if (CollectionUtils.isNotEmpty(values)) {
                    result.add(values.get(0));
                }
            });

            List<SamplingBox> page = ListUtil.page(param.getPageNum() - 1, param.getPageSize(), result);
            page.forEach(this::buildInfo);
            return new PageInfo<>(param.getPageNum(), param.getPageSize(), page, list.size());
        }
    }

    private void buildInfo(SamplingBox item) {
        Integer samplingNum = samplingBoxRecordMapper.countSamplingNum(item.getId());
        if (samplingNum != null) {
            item.setSamplingNum(samplingNum);
        }
        Batch batch = batchMapper.selectById(item.getBatchId());
        if (batch != null) {
            item.setBatchCode(batch.getCode());
            item.setSendTime(batch.getCreateTime());
        }
    }

    /**
     * 查询采样盒子
     *
     * @param id 采样盒子主键
     * @return 采样盒子
     */
    public SamplingBox getById(Long id) {
        return samplingBoxMapper.selectById(id);
    }

    /**
     * 查询采样盒子列表
     *
     * @param samplingBox 采样盒子
     * @return 采样盒子
     */
    public List<SamplingBox> selectList(SamplingBox samplingBox) {
        List<SamplingBox> list = samplingBoxMapper.selectList(samplingBox);
        list.forEach(this::buildInfo);
        return list;
    }

    /**
     * 保存采样盒子
     *
     * @param samplingBox 采样盒子
     * @return 结果
     */
    public Boolean save(SamplingBox samplingBox) {
        if (samplingBox.getId() != null) {
            samplingBoxMapper.update(samplingBox);
            return true;
        }
        samplingBoxMapper.insert(samplingBox);
        return true;
    }

    /**
     * 批量删除采样盒子
     *
     * @param ids 需要删除的采样盒子主键
     * @return 结果
     */
    public Boolean deleteByIds(String ids) {
        samplingBoxMapper.deleteByIds(Convert.toStrArray(ids));
        return true;
    }

    ///**
    // * 寄样
    // * @param param
    // * @return
    // */
    //@Transactional(rollbackFor = Exception.class)
    //public Boolean sendSamples(SendSamplesParam param) {
    //    AssertUtil.assertNotNull(param.getExpress(), "快递单号为空");
    //    AssertUtil.assertNotEmpty(param.getSamplingBoxIds(), "寄样盒子为空");
    //    for (Long id : param.getSamplingBoxIds()) {
    //        SamplingBox samplingBox = samplingBoxMapper.selectById(id);
    //        AssertUtil.assertNotNull(samplingBox, "非法的盒子id="+id);
    //        samplingBoxMapper.update(samplingBox);
    //    }
    //    return true;
    //}

    /**
     * 更新状态
     * @param param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(SamplingBox param) {
        samplingBoxMapper.update(param);
        List<SamplingRecord> list = samplingRecordMapper.queryByBoxId(param.getId());
        for (SamplingRecord item : list) {
            item.setSampleStatus(param.getStatus());
            samplingRecordMapper.update(item);
        }
        return true;
    }
}
